package com.aiyan.edu.framework.exception;

import com.aiyan.edu.framework.model.response.CommonCode;
import com.aiyan.edu.framework.model.response.ResultCode;
import com.aiyan.edu.framework.model.response.ResponseResult;
import com.google.common.collect.ImmutableMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 统一异常捕获类
 *
 * @author: zqzhou
 * @create: 2019/10/08 23:18
 **/
@ControllerAdvice
public class ExceptionCatcher {

    private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionCatcher.class);

    /**
     * 定义异常map，绑定异常类型对应的错误代码
     */
    private static ImmutableMap<Class<? extends Throwable>, ResultCode> EXCEPTIONS;

    /**
     * 定义map的build对象，构建ImmutableMap
     */
    protected static ImmutableMap.Builder<Class<? extends Throwable>, ResultCode> builder = ImmutableMap.builder();

    /**
     * 定义异常类型所对应的错误代码
     */
    static {
        builder.put(HttpMessageNotReadableException.class, CommonCode.INVALID_PARAM);
    }

    /**
     * 捕获CustomException类型异常
     *
     * @param customeException
     * @return
     */
    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public ResponseResult customeException(CustomException customeException) {
        LOGGER.error("catch exception:{}", customeException.getMessage());
        customeException.printStackTrace();
        return new ResponseResult(customeException.getResultCode());
    }

    /**
     * 捕获Exception类型异常
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseResult exception(Exception exception) {
        LOGGER.error("catch exception:{}", exception.getMessage());
        exception.printStackTrace();
        if (EXCEPTIONS == null) {
            EXCEPTIONS = builder.build();
        }

        ResultCode resultCode = EXCEPTIONS.get(exception.getClass());
        if (null == resultCode) {
            return new ResponseResult(CommonCode.SERVER_ERROR);
        }

        return new ResponseResult(resultCode);
    }
}
